package org.xhy.oap.web;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ElasticsearchQueryService {

    @Autowired
    private RestHighLevelClient client;

    // 查询索引中的所有数据
    public List<Map<String, Object>> searchByTraceId(String indexName, String traceId) throws IOException {
        // 创建搜索请求，指定索引名称
        SearchRequest searchRequest = new SearchRequest(indexName);

        // 构建查询条件：matchQuery() 查询指定的 traceId
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("traceId", traceId)); // 用 matchQuery 查询特定 traceId
        searchRequest.source(searchSourceBuilder);

        // 执行搜索请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 提取搜索结果
        List<Map<String, Object>> results = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            results.add(hit.getSourceAsMap());
        }

        return results;
    }

    public List<Map<String, Object>> searchAllData(String indexName) throws IOException {
        // 创建搜索请求，指定索引名称
        SearchRequest searchRequest = new SearchRequest(indexName);

        // 构建查询条件：matchAllQuery() 查询所有文档
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);

        // 执行搜索请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 提取搜索结果
        List<Map<String, Object>> results = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            results.add(hit.getSourceAsMap());
        }

        return results;
    }

}
